﻿using System.Web.UI.WebControls;

/// <summary>
/// Created By : Nguyen Dinh Tuong Uyen
/// Created Date : 02/22/2012
/// Description : Includes method help for uploading file
/// </summary>
/// 
namespace Common
{
    public class UploadFileHelper
    {
        public UploadFileHelper() { }

        private static string extensionImage = ";jpg;png;gif;jpeg;";  

        private static bool CheckExtension(string fileName, string listExtensionAllow)
        {
            string ext = FileHelper.GetExtension(fileName);
            if (listExtensionAllow == "*")
                return true;

            if (listExtensionAllow != "")
                return listExtensionAllow.Contains(";" + ext + ";");          

            return false;

        }

        /// <summary>
        /// Upload image file to Upload folder
        /// </summary>
        /// <param name="controlUpload"></param>
        /// <param name="returnError"></param>
        /// <returns></returns>
        public static string SaveFile(FileUpload controlUpload ,string folderPath, ref string returnError)  //return filePath
        {
            return SaveFile(controlUpload, folderPath, extensionImage, true, ref returnError);
        }

        public static string SaveFile(FileUpload controlUpload, string folderSave, string listExtensionAllow, bool UnZip, ref string returnError)
        {
            returnError = "";

            if (controlUpload.HasFile)  //Neu co file upload len
            {
                string filePath = "";
                string sMapPath = folderSave;
                string strName = controlUpload.FileName;
                string ext = FileHelper.GetExtension(strName);

                if (CheckExtension(strName, listExtensionAllow))
                {
                    while (FileHelper.Exist(sMapPath + strName)) //check file exist
                    {
                        strName = strName.Replace(".", CommonHelper.RanNum(2) + ".");
                    }
                    controlUpload.SaveAs(sMapPath + strName);  //upload file to server

                    filePath = sMapPath + strName;              //get absulute file path       

                    return filePath;
                }

                else  //file upload len ko cho phep
                {
                    returnError = "File extension is not allowed";
                    return "";
                }
            }

            else  //chua chon file upload
            {
                returnError = "Please choose file to upload";
                return "";
            }
        }
    }
}